// reference:https://dev.to/thanasistraitsis/flutter-image-upload-and-image-crop-5hgp

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart' as getPack;
import 'package:get/get_core/src/get_main.dart' as getPart;
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import '../../../event/DataCallBack.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../utils/CommonUtil.dart';
import '../../../utils/tips.dart';
import '../../../views/controller/MineViewController.dart';
import '../controllers/mine_profile_controller.dart';
import './image_container.dart';
import 'package:dio/dio.dart' ;

class AvatarScreen extends StatefulWidget {
  final String name;
  final String avatarUrl;
  final String id;
  AvatarScreen(this.name,this.avatarUrl,this.id);
  // const AvatarScreen(String name, {super.key});

  @override
  State<AvatarScreen> createState() => _AvatarScreenState();
}

File? file; //file是一个临时状态量，用来控制是否上传

class _AvatarScreenState extends State<AvatarScreen> {

  Future uploadImage(ImageSource source) async {
    final image = await ImagePicker().pickImage(
      source: source,
    );
    if (image == null) return;

    File imageFile = File(image.path);

    var croppedFile = await cropImage(imageFile);
    // await sendImage(croppedFile);
    setState(() {
      file = croppedFile;
    });
  }

  Future<File?> cropImage(File pickedFile) async {
    final croppedFile = await ImageCropper().cropImage(
      sourcePath: pickedFile.path,
      compressFormat: ImageCompressFormat.jpg,
      compressQuality: 100,
      uiSettings: [
        AndroidUiSettings(
          toolbarTitle: '图片裁剪',
          initAspectRatio: CropAspectRatioPreset.original,
          lockAspectRatio: false,
        ),
        IOSUiSettings(
          title: '图片裁剪',
          doneButtonTitle: '确定',
          cancelButtonTitle: '取消'
        ),
      ],
    );

    if (croppedFile != null) {
     await sendImage(croppedFile.path);
      return File(croppedFile.path);
    } else {
      print('pickedFile $pickedFile');
      // 用户没有选择的话不需要上传
      // await sendImage(pickedFile.path);
      return File(pickedFile.path);
    }
  }

  // 将图片发送到后端
  Future<void> sendImage(path) async{
    Tips.showLoading();
    String fetchPicPre = CommonUtil.getInterfaceUrl();
    String picUrl = '$fetchPicPre/sys/common/upload';
    String? loginToken = CommonUtil.getCurrentLoginToken();
    BaseOptions options = BaseOptions();
    options.headers["contentType"]="multipart/form-data";
    options.headers["authorization"]=loginToken;
    options.headers["x-access-token"]=loginToken;
    try {
      Dio dio = new Dio(options);
      FormData formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(path),
      });

      Response response = await dio.post(picUrl, data: formData);

      // 处理服务器返回的响应数据
      if (response.statusCode == 200) {
        // 上传成功
        var url = response.data["message"];
        EditPic(url,widget.id,path);
      } else {
        // 上传失败
        Tips.dismissLoading();
        Tips.showToast('$response.data');
      }
    } catch (error) {
      Tips.dismissLoading();
      // 异常处理
      Tips.showToast('$error');
    }
  }

Future<void> EditPic(url,id,path) async{
  NetWorkManager.getInstance().requestBussiness(
      NetWorkManager.Edit_INFOS, {
    'id':id,
    'avatar':url
  }, NetWorkManager.methodPOST, DataCallBack(
      businessCallBack: (v) {
        Tips.dismissLoading();
        final mineViewController= getPack.Get.find<MineViewController>();
        final mineProfileController = getPack.Get.find<MineProfileController>();
        mineViewController.updateAvatar(url);
        // mineProfileController.updateAvatar(url);
        mineProfileController.updateLocalAvatar(path);
      },
      errorCallBack: (v) {
        Tips.dismissLoading();
        Tips.showToast(v);
      }

  ));
}

  @override
  Widget build(BuildContext context) {
    return Center(
        child:
        GestureDetector(onTap:(){
          uploadImage(ImageSource.gallery);
        },child:Stack(
          alignment: const Alignment(0.9, 0.9),
          children: [
            ImageContainer(
              name:widget.name,
              file: file,
              avatarUrl:widget.avatarUrl,
            ),
            Container(
                  child: Image.asset('assets/images/icon_camera.png',width: 24,height: 24,),
            ),
          ],
        ),)

      );
  }
}